/**
 * useTabHotkeys - Keyboard Shortcuts for Tab Navigation
 * 
 * Shortcuts:
 * - Ctrl+Tab: Next session
 * - Ctrl+Shift+Tab: Previous session
 * - Ctrl+W: Close current session
 * - Ctrl+T: New session
 * - Ctrl+1-9: Jump to session by index
 */

import { useEffect } from 'react';
import { useSessionStore } from '@/store/session';

export interface UseTabHotkeysOptions {
  enabled?: boolean;
}

export function useTabHotkeys(options: UseTabHotkeysOptions = {}) {
  const { enabled = true } = options;
  
  const {
    sessions,
    currentSession,
    loadSession,
    createSession,
    deleteSession,
  } = useSessionStore();

  useEffect(() => {
    if (!enabled) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      // Check if we're in an input/textarea
      const target = e.target as HTMLElement;
      const isInput = target.tagName === 'INPUT' || 
                      target.tagName === 'TEXTAREA' || 
                      target.isContentEditable;

      // Ctrl/Cmd+Tab: Next session
      if ((e.ctrlKey || e.metaKey) && e.key === 'Tab' && !e.shiftKey) {
        e.preventDefault();
        switchToNextSession();
        return;
      }

      // Ctrl/Cmd+Shift+Tab: Previous session
      if ((e.ctrlKey || e.metaKey) && e.key === 'Tab' && e.shiftKey) {
        e.preventDefault();
        switchToPreviousSession();
        return;
      }

      // Ctrl/Cmd+W: Close current session (only when not in input)
      if ((e.ctrlKey || e.metaKey) && e.key === 'w' && !isInput) {
        e.preventDefault();
        closeCurrentSession();
        return;
      }

      // Ctrl/Cmd+T: New session (only when not in input)
      if ((e.ctrlKey || e.metaKey) && e.key === 't' && !isInput) {
        e.preventDefault();
        createNewSession();
        return;
      }

      // Ctrl/Cmd+1-9: Jump to session by index (only when not in input)
      if ((e.ctrlKey || e.metaKey) && /^[1-9]$/.test(e.key) && !isInput) {
        e.preventDefault();
        const index = parseInt(e.key) - 1;
        switchToSessionByIndex(index);
        return;
      }
    };

    const switchToNextSession = () => {
      if (sessions.length === 0) return;

      const currentIndex = sessions.findIndex(s => s.id === currentSession?.id);
      const nextIndex = (currentIndex + 1) % sessions.length;
      
      loadSession(sessions[nextIndex].id).catch(err => {
        console.error('Failed to switch to next session:', err);
      });
    };

    const switchToPreviousSession = () => {
      if (sessions.length === 0) return;

      const currentIndex = sessions.findIndex(s => s.id === currentSession?.id);
      const prevIndex = currentIndex <= 0 ? sessions.length - 1 : currentIndex - 1;
      
      loadSession(sessions[prevIndex].id).catch(err => {
        console.error('Failed to switch to previous session:', err);
      });
    };

    const closeCurrentSession = () => {
      if (!currentSession) return;

      const currentIndex = sessions.findIndex(s => s.id === currentSession.id);
      
      // Switch to next or previous session before closing
      if (sessions.length > 1) {
        const nextIndex = currentIndex < sessions.length - 1 ? currentIndex + 1 : currentIndex - 1;
        loadSession(sessions[nextIndex].id).then(() => {
          return deleteSession(currentSession.id);
        }).catch(err => {
          console.error('Failed to close session:', err);
        });
      } else {
        // Last session, create new one before closing
        createNewSession().then(() => {
          return deleteSession(currentSession.id);
        }).catch(err => {
          console.error('Failed to close session:', err);
        });
      }
    };

    const createNewSession = () => {
      createSession('新对话').catch(err => {
        console.error('Failed to create session:', err);
      });
    };

    const switchToSessionByIndex = (index: number) => {
      if (index >= 0 && index < sessions.length) {
        loadSession(sessions[index].id).catch(err => {
          console.error('Failed to switch to session by index:', err);
        });
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [enabled, sessions, currentSession, loadSession, createSession, deleteSession]);
}

